from LeetCoder import *


class Solution:
    def findMaxFish(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        visit = [[False] * n for _ in range(m)]

        def f(i, j):
            if i < 0 or i == m or j < 0 or j == n:
                return 0
            if grid[i][j] == 0:
                return 0
            if visit[i][j]:
                return 0
            visit[i][j] = True
            return grid[i][j] + f(i+1, j) + f(i-1, j) + f(i, j+1)+f(i, j-1)
        ans = -inf
        for i in range(m):
            for j in range(n):
                if grid[i][j] != 0 and not visit[i][j]:
                    ans = max(ans, f(i, j))
        return ans


s = Solution()
print(s.findMaxFish([[0, 2, 1, 0], [4, 0, 0, 3], [1, 0, 0, 4], [0, 3, 2, 0]]))
print(s.findMaxFish([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]]))
